package org.martin.snsrs.daos;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.martin.snsrs.beans.Activity;
import org.martin.snsrs.beans.ActivityTags;
import org.martin.snsrs.beans.User;
import org.martin.snsrs.beans.UserComment;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class ActivityDao {
	private Session session;
	
	private SessionFactory sessionFactory;
	
	private HibernateTemplate hibernateTemplate;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		hibernateTemplate = new HibernateTemplate(sessionFactory);
		session = sessionFactory.openSession();
	}
	
	public void saveActivity(Activity activity){
		hibernateTemplate.save(activity);
		hibernateTemplate.flush();
	}
	
	public Activity getActivity(Integer activityID){
		return (Activity)hibernateTemplate.get("Activities", activityID);
	}
	
	public Activity getActivityByName(String activityName){
		Criteria criteria = session.createCriteria(Activity.class);
		criteria.add(Restrictions.eq("activityName", activityName));
		List<Activity> activities = criteria.list();
		if(activities != null && activities.size() > 0)
			return activities.get(0);
		else {
			return null;
		}
	}
	
	public List<Activity> gteActivitiesByTag(String tagName){
		Criteria criteria = session.createCriteria(ActivityTags.class);
		criteria = criteria.createCriteria("tags");
		criteria.add(Restrictions.eq("tagName", tagName));
		List<Activity> activities = new ArrayList();
		List<ActivityTags> activityTags = criteria.list();
		for(ActivityTags tag : activityTags){
			activities.add(tag.getActivities());
		}
		return activities;
	}
	
	public void saveUserComment(UserComment userComment){
		hibernateTemplate.save(userComment);
	}
	
	public List<UserComment> getUserCommentByUserID(User user){
		Criteria criteria = session.createCriteria(UserComment.class);
		criteria.add(Restrictions.eq("user", user));
		return criteria.list();
	}
	
	public List<UserComment> getUserCommentByActivityID(Activity activity){
		Criteria criteria = session.createCriteria(UserComment.class);
		criteria.add(Restrictions.eq("activity", activity));
		return criteria.list();
	}
}
